package com.sky.aspect;

import com.sky.annotations.AutoFill;
import com.sky.constant.AutoFillConstant;
import com.sky.context.BaseContext;
import com.sky.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.time.LocalDateTime;
import java.util.Arrays;

@Aspect
@Slf4j
@Component
public class AutoFillAspect {
    @Pointcut("execution(* com.sky.mapper.*.*(..)) && @annotation(com.sky.annotations.AutoFill)")
    public void autoFillPointcut() {
    }


    @Before("autoFillPointcut()")
    public void autoFill(JoinPoint joinPoint) {

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String methodName = method.getName();
        AutoFill autoFill = method.getAnnotation(AutoFill.class);
        OperationType fillType = autoFill.value();
        Object[] args = joinPoint.getArgs();
        if (args == null || args.length == 0) {
            return;
        }
        log.info("拦截的方法名 {} 参数 {}",methodName, Arrays.toString(args));

        Object entity = args[0];

        Class<?> entityClass = entity.getClass();

        LocalDateTime now = LocalDateTime.now();
        Long userId = BaseContext.getId();


        if (fillType.equals(OperationType.INSERT)) {
            log.info("触发Insert");
            try {
                Method setCreateTime = entityClass.getDeclaredMethod(AutoFillConstant.setCreateTime, LocalDateTime.class);
                Method setUpdateTime = entityClass.getDeclaredMethod(AutoFillConstant.setUpdateTime, LocalDateTime.class);
                Method setCreateUser = entityClass.getDeclaredMethod(AutoFillConstant.setCreateUser, Long.class);
                Method setUpdateUser = entityClass.getDeclaredMethod(AutoFillConstant.setUpdateUser, Long.class);

                setCreateTime.invoke(entity, now);
                setUpdateTime.invoke(entity, now);
                setCreateUser.invoke(entity, userId);
                setUpdateUser.invoke(entity, userId);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        } else {
            log.info("触发Update");
            try {
                Method setUpdateTime = entityClass.getDeclaredMethod(AutoFillConstant.setUpdateTime, LocalDateTime.class);
                Method setUpdateUser = entityClass.getDeclaredMethod(AutoFillConstant.setUpdateUser, Long.class);

                setUpdateTime.invoke(entity, now);
                setUpdateUser.invoke(entity, userId);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
